package com.htht.smartschool.service.fence;

import java.util.ArrayList;
import java.util.List;

import com.htht.smartschool.amq.SeniorMessageSender;
import com.htht.smartschool.common.service.BaseService;
import com.htht.smartschool.model.card.TCard;
import com.htht.smartschool.model.fence.Gps;
import com.htht.smartschool.model.fence.TFence;
import com.htht.smartschool.model.student.TStudent;
import com.htht.smartschool.model.tschool.TSchool;
import com.htht.smartschool.service.card.CardService;
import com.htht.smartschool.util.system.PositionUtil;

public class FenceService extends BaseService{

	@SuppressWarnings("unchecked")
	public List<TFence> getFenceByStudentCode(TFence fence) {
		String sql = "SELECT id,fencepoint,fenceradius,type,fencecode,studentcode,remark,alarmway from t_fence"
				+ " tf where tf.studentcode = :studentcode";
		if(fence.getFencecode() != null && !fence.getFencecode().equalsIgnoreCase("null")){
			sql += " and tf.fencecode = :fencecode";
		}
		List<Object[]> list = getDao().queryBySQL(sql,fence);
		List<TFence> result = new ArrayList<TFence>();
		for (int i = 0; i < list.size(); i++) {
			Object[] obj = list.get(i);
			TFence f = new TFence();
			f.setId(Long.valueOf(String.valueOf(obj[0])));
			f.setFencepoint(String.valueOf(obj[1]));
			f.setFenceradius(String.valueOf(obj[2]));
			f.setType(String.valueOf(obj[3]));
			f.setFencecode(String.valueOf(obj[4]));
			f.setStudentcode(String.valueOf(obj[5]));
			f.setRemark(String.valueOf(obj[6]));
			f.setAlarmway(String.valueOf(obj[7]));
			result.add(f);
		}
		return result;
	}
	public boolean initFences(TFence f) {
		if(f.getStudentcode() != null && f.getStudentcode().length() > 0){
			TSchool ts = getSchoolFenceByStudentCode(f.getStudentcode());
			TFence tf = new TFence(ts.getCenter(), ts.getRadius(), "1", "1", f.getStudentcode(), "学校");
			setFenceToCard(tf,"ON");
			if(f.getFencepoint() != null && f.getFencepoint().length() > 0 &&
					f.getFenceradius() != null && f.getFenceradius().length() > 0){
				f.setFencecode(String.valueOf(2));
				f.setRemark("家");
				add(f);
				String sql = "delete from t_fence where studentcode = "+f.getStudentcode()+" and fencecode > 2";
				getDao().executeSQL(sql);
			}
			return true;
		}else{
			return false;
		}
		
	}
	public boolean addFenceByStudentCode(TFence f) {
		boolean flag = false;
		Double radius = Double.valueOf(f.getFenceradius());
		Long rad = Math.round(radius);
		f.setFenceradius(String.valueOf(rad));
		List<TFence> list = getFenceByStudentCode(f);
		if(list == null || list.size() ==0){
			f.setFencecode(String.valueOf(2));
			boolean result = add(f);//添加
			if(result){
				flag = true;
			}
		}else{
			if(list.size() == 5){
				if(f.getFencecode() != null && f.getFencecode().length() >0){
					update(f);
				}
				flag = false;
			}else{
				List<Integer> li = new ArrayList<Integer>();
				for (int i = 0; i < list.size(); i++) {
					TFence fence = list.get(i);
					li.add(Integer.parseInt(fence.getFencecode()));
				}
				if(f.getFencecode() != null && f.getFencecode().length() >0){
					update(f);
				}else{
					if(!li.contains(2)){
						f.setFencecode(String.valueOf(2));
						add(f);
					}else if(!li.contains(3)){
						f.setFencecode(String.valueOf(3));
						add(f);
					}else if(!li.contains(4)){
						f.setFencecode(String.valueOf(4));
						add(f);
					}else if(!li.contains(5)){
						f.setFencecode(String.valueOf(5));
						add(f);
					}
				}
				flag = true;
			}
		}
		return flag;
	}

	public boolean  add(TFence f){
		boolean flag = false;
		boolean result = setFenceToCard(f,"ON");
		if(result){
			flag = true;
		}
		List<TFence> listtf = getFenceByStudentCode(f);
		if(listtf.size() >0){
			update(f);
		}else{
			String sql = "INSERT INTO t_fence VALUES (null,:fencepoint,:fenceradius,:type,:fencecode,:studentcode,:remark,:alarmway)";
			getDao().executeSQL(sql,f);
		}
		return flag;
	}
	public void update(TFence f){
		setFenceToCard(f,"ON");
		String sql = "UPDATE t_fence set fenceradius=:fenceradius,type=:type,"
				+ "remark=:remark,alarmway=:alarmway WHERE studentcode=:studentcode and fencecode = :fencecode";
		getDao().executeSQL(sql,f);
	}
	public boolean setFenceToCard(TFence f,String flag){
		boolean result = false;
		String fenccode = f.getFencecode();
		String type = "";
		if(f.getType().equalsIgnoreCase("2")){
			type = "IN";
		}else if(f.getType().equalsIgnoreCase("3")){
			type = "OUT";
		}
		String[] lonlat = f.getFencepoint().split(",");
		Gps gps = PositionUtil.gcj_To_Gps84(Double.valueOf(lonlat[0]),Double.valueOf(lonlat[1]));
		String lon = "E"+gps.getWgLon();
		String lat = "N"+gps.getWgLat();
		if(lon.contains("-")){
			lon = "W"+lon.substring(2, lon.length());
		}
		if(lat.contains("-")){
			lat = "S"+lat.substring(2, lat.length());
		}
		CardService cs = new CardService();
		TCard card = cs.getCardByStudentCode(f.getStudentcode());
		if(card != null){
			String mess = card.getImei()+":GFENCE:GFENCE,"+fenccode+","+flag+",0,"+lat+","+lon+","+f.getFenceradius()+","+type+","+f.getAlarmway()+"#";
			SeniorMessageSender.sendMessage(mess);
			result = true;
		}
		return result;
	}
	public String dealPoint(String f){
		String pointStr = f.substring(6,f.length()-1);
		String[] point = pointStr.split(" ");
		return point[0]+","+point[1];
	}
	
	@SuppressWarnings({ "unused", "unchecked" })
	private List<TFence> getFenceDetail(TFence tfence) {
		List<TFence> fence = null;
		try {
			String hql = String.format("from TFence where %1$s='%2$s'", "fencecode", tfence.getFencecode());
			fence =  getDao().queryByHQL(hql,tfence);
			if (fence == null) {
			} 
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fence;
	}

	public boolean updateFenceByStudentCode(TFence f) {
		Double radius = Double.valueOf(f.getFenceradius());
		Long rad = Math.round(radius);
		f.setFenceradius(String.valueOf(rad));
		String sql = "UPDATE t_fence tf SET ";
		if(f.getFencepoint()!=null){
			String[] points = f.getFencepoint().split(",");
			sql += " tf.fencepoint = :fencepoint ";
			f.setFencepoint(points[0]+","+points[1]);
		}
		if(f.getFenceradius() != null){
			sql += " , tf.fenceradius = :fenceradius ";
		}
		if(f.getRemark() != null){
			sql += " , tf.remark = :remark ";
		}
		if(f.getType() != null){
			sql += " , tf.type = :type ";
		}
		if(f.getAlarmway() != null){
			sql +=", tf.alarmway = :alarmway ";
		}
		sql += " where tf.fencecode = :fencecode and tf.studentcode = :studentcode";
		int n = getDao().executeSQL(sql,f);
		setFenceToCard(f,"ON");
		boolean flag = false;
		if(n != -1){
			flag = true;
		}
		return flag;
	}

	public boolean deleteFenceByStudentCode(TFence f) {
		boolean flag = false;
		List<TFence> list = getFenceByStudentCode(f);
		if(list.size()>0){
			TFence tf = list.get(0);
			setFenceToCard(tf,"OFF");
			String sql = "delete from t_fence where fencecode = :fencecode and studentcode = :studentcode";
			int n = getDao().executeSQL(sql,f);
			if(n != -1){
				flag = true;
			}
		}
		return flag;
	}

	@SuppressWarnings("unchecked")
	public TSchool getSchoolFenceByStudentCode(String studentcode) {
		String sql = "SELECT ts.* FROM t_school ts,(SELECT * FROM t_student WHERE studentcode = :studentcode) tx WHERE tx.schoolid = ts.schoolcode ";
		TStudent tstudent = new TStudent();
		tstudent.setStudentcode(studentcode);
		List<Object[]> list = getDao().queryBySQL(sql,tstudent);
		if(list.size() > 0){
			Object[] obj =list.get(0);
			TSchool ts = new TSchool(String.valueOf(obj[1]), String.valueOf(obj[2]),String.valueOf(obj[3]), 
					String.valueOf(obj[4]), String.valueOf(obj[5]), String.valueOf(obj[6]));
			return ts;

		}else{
			return null;
		}
		
	}

	@SuppressWarnings("unchecked")
	public TFence getFenceByStudentImei(TFence fence) {
		String sql = "SELECT tf.* FROM t_card tc,t_fence tf WHERE"
				+ " tc.imei = :imei AND tf.fencecode = :fencecode AND tc.studentcode = tf.studentcode";
		List<Object[]> list = getDao().queryBySQL(sql,fence);
		if(list.size()>0){
			Object[] obj = list.get(0);
			TFence f = new TFence();
			f.setId(Long.valueOf(String.valueOf(obj[0])));
			f.setFencepoint(String.valueOf(obj[1]));
			f.setFenceradius(String.valueOf(obj[2]));
			f.setType(String.valueOf(obj[3]));
			f.setFencecode(String.valueOf(obj[4]));
			f.setStudentcode(String.valueOf(obj[5]));
			f.setRemark(String.valueOf(obj[6]));
			f.setAlarmway(String.valueOf(obj[7]));
			return f;
		}else{
			return null;
		}
	}

}
